﻿using Microsoft.Ccr.Core;

namespace BitTorrent.Agents {
    public class AgentBase : CcrServiceBase {
        private Port<Shutdown> _cleanupPort = new Port<Shutdown>();

        protected AgentBase(DispatcherQueue dispatcherQueue)
            : base(dispatcherQueue) {
        } 

        protected Port<Shutdown> CleanupPort { get { return _cleanupPort; } set { _cleanupPort = value; } }

        protected Receiver<Shutdown> Cleanup(Handler cleanupCode) {
            return Arbiter.Receive(false, _cleanupPort,
                msg => {
                    try {
                        cleanupCode();
                    }
                    finally {
                        _cleanupPort.Post(msg);
                    }
                });
        }

        protected Receiver<Shutdown> Cleanup(Handler<Shutdown> cleanupCode) {
            return Arbiter.Receive(false, _cleanupPort,
                msg => {
                    try {
                        cleanupCode(msg);
                    }
                    finally {
                        _cleanupPort.Post(msg);
                    }
                });
        }
    }
}